import React, { useState } from 'react';
import { 
  Form, 
  Input, 
  Button, 
  Card, 
  message, 
  Space,
  Typography,
  Divider,
  Checkbox
} from 'antd';
import { 
  ArrowLeftOutlined, 
  UserOutlined, 
  LockOutlined,
  EyeInvisibleOutlined,
  EyeTwoTone
} from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import styled from '@emotion/styled';

const { Title, Text } = Typography;

interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
}

// Styled Components
const LoginContainer = styled.div`
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
  position: relative;
`;

const BackButton = styled(Button)`
  position: absolute;
  top: 20px;
  left: 20px;
  color: #fff;
  border: 1px solid rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  
  &:hover {
    background: rgba(255, 255, 255, 0.2);
    border-color: rgba(255, 255, 255, 0.5);
    color: #fff;
  }
`;

const LoginContent = styled.div`
  width: 100%;
  max-width: 400px;
`;

const StyledCard = styled(Card)`
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  background: rgba(255, 255, 255, 0.95);
  
  .ant-card-body {
    padding: 40px 32px;
  }
`;

const LoginHeader = styled.div`
  text-align: center;
  margin-bottom: 32px;
  
  h2 {
    margin-bottom: 8px;
    color: #1f2937;
    font-weight: 600;
  }
`;

const LoginButton = styled(Button)`
  height: 48px;
  border-radius: 8px;
  font-weight: 500;
  font-size: 16px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  
  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
  }
`;

const LoginLink = styled(Link)`
  color: #667eea;
  font-weight: 500;
  
  &:hover {
    color: #5a6fd8;
  }
`;

const LoginFooter = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
`;

const ForgotPasswordLink = styled(LoginLink)`
  font-size: 14px;
`;

const RegisterSection = styled.div`
  text-align: center;
  margin-top: 16px;
`;

const StyledInput = styled(Input)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledPasswordInput = styled(Input.Password)`
  border-radius: 6px;
  border: 1px solid #d1d5db;
  transition: all 0.3s;
  
  &:hover,
  &:focus,
  &.ant-input-affix-wrapper-focused {
    border-color: #667eea;
    box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
  }
`;

const StyledFormItem = styled(Form.Item)`
  .ant-form-item-label {
    font-weight: 500;
    
    > label {
      color: #374151;
    }
  }
  
  .ant-checkbox-wrapper {
    color: #374151;
  }
`;

const StyledDivider = styled(Divider)`
  color: #9ca3af;
  
  &::before,
  &::after {
    border-top: 1px solid #e5e7eb;
  }
`;

const SocialLoginSection = styled.div`
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 20px;
`;

const SocialButton = styled(Button)`
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: 1px solid #d1d5db;
  
  &:hover {
    border-color: #667eea;
    color: #667eea;
  }
`;

// 响应式样式 - 修复Emotion组件选择器问题
const MobileWrapper = styled.div`
  @media (max-width: 480px) {
    /* 移除组件选择器，使用类名选择器替代 */
    .login-container {
      padding: 16px;
    }
    
    .back-button {
      top: 16px;
      left: 16px;
    }
    
    .styled-card .ant-card-body {
      padding: 24px 20px;
    }
    
    .login-footer {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;
    }
  }
`;

const SignInPage: React.FC = () => {
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const handleBack = () => {
    navigate(-1); // 返回上一页
  };

  const onFinish = async (values: LoginFormValues) => {
    setLoading(true);
    try {
      // 模拟登录API调用
      await mockLoginApi(values);
      message.success('登录成功！');
      // 登录成功后跳转到首页或其他页面
      navigate('/dashboard');
    } catch (error) {
      message.error('登录失败，请检查用户名和密码');
    } finally {
      setLoading(false);
    }
  };

  const mockLoginApi = (values: LoginFormValues): Promise<void> => {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 模拟登录验证
        if (values.username && values.password) {
          // 保存记住我状态
          if (values.remember) {
            localStorage.setItem('rememberMe', 'true');
          }
          resolve();
        } else {
          reject(new Error('登录失败'));
        }
      }, 1500);
    });
  };

  const handleForgotPassword = () => {
    navigate('/forgotPassword');
    // message.info('忘记密码功能即将开放');
  };

  const handleSocialLogin = (provider: string) => {
    message.info(`${provider} 登录功能即将开放`);
  };

  return (
    <MobileWrapper>
      <LoginContainer className="login-container">
        <BackButton 
          type="text" 
          icon={<ArrowLeftOutlined />} 
          onClick={handleBack}
          className="back-button"
        >
          返回
        </BackButton>
        
        <LoginContent>
          <StyledCard className="styled-card">
            <LoginHeader>
              <Title level={2}>欢迎回来</Title>
              <Text type="secondary">请登录您的账号</Text>
            </LoginHeader>

            <Form
              form={form}
              name="login"
              onFinish={onFinish}
              layout="vertical"
              size="large"
              initialValues={{
                remember: true
              }}
            >
              <StyledFormItem
                name="username"
                label="用户名或邮箱"
                rules={[
                  { required: true, message: '请输入用户名或邮箱!' }
                ]}
              >
                <StyledInput 
                  prefix={<UserOutlined />} 
                  placeholder="请输入用户名或邮箱" 
                />
              </StyledFormItem>

              <StyledFormItem
                name="password"
                label="密码"
                rules={[
                  { required: true, message: '请输入密码!' }
                ]}
              >
                <StyledPasswordInput
                  prefix={<LockOutlined />}
                  placeholder="请输入密码"
                  iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
                />
              </StyledFormItem>

              <LoginFooter className="login-footer">
                <StyledFormItem name="remember" valuePropName="checked" noStyle>
                  <Checkbox>记住我</Checkbox>
                </StyledFormItem>
                <ForgotPasswordLink to="#" onClick={handleForgotPassword}>
                  忘记密码?
                </ForgotPasswordLink>
              </LoginFooter>

              <Form.Item>
                <LoginButton 
                  type="primary" 
                  htmlType="submit" 
                  loading={loading}
                  block
                >
                  登录
                </LoginButton>
              </Form.Item>
            </Form>

            <StyledDivider plain>或使用以下方式登录</StyledDivider>

            <SocialLoginSection>
              <SocialButton 
                icon={<span style={{ fontSize: '18px' }}>G</span>}
                onClick={() => handleSocialLogin('Google')}
              />
              <SocialButton 
                icon={<span style={{ fontSize: '18px' }}>f</span>}
                onClick={() => handleSocialLogin('Facebook')}
              />
              <SocialButton 
                icon={<span style={{ fontSize: '18px' }}>微</span>}
                onClick={() => handleSocialLogin('微信')}
              />
            </SocialLoginSection>

            <RegisterSection>
              <Space>
                <Text>还没有账号?</Text>
                <LoginLink to="/register">立即注册</LoginLink>
              </Space>
            </RegisterSection>
          </StyledCard>
        </LoginContent>
      </LoginContainer>
    </MobileWrapper>
  );
};

export default SignInPage;